//
//  Filter.m
//  JFTwxsd
//
//  Created by Steven on 2018/9/20.
//  Copyright © 2018年 junfeiweiyejiaoyujituan. All rights reserved.
//


#import "Filter.h"

/**
 高斯模糊滤镜
 */
Filter blur(double radius){

    return ^(CIImage *image){
      
        NSDictionary *param = @{kCIInputRadiusKey: @(radius),
                                kCIInputImageKey: image};
        CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur" withInputParameters:param];
        return filter.outputImage;
    };
}
/**
 颜色层叠滤镜
 */
Filter colorGenerator(UIColor *color){
    
    return ^(CIImage *image){
        
        CIColor *c = [[CIColor alloc]initWithColor:color];
        NSDictionary *param = @{kCIInputColorKey: c};
        CIFilter *filter = [CIFilter filterWithName:@"CIConstantColorGenerator" withInputParameters:param];
        return filter.outputImage;
    
    };
}

/**
 合成滤镜
 */
Filter compositeSourceOver(CIImage *overlay){
    
    return ^(CIImage *image){
        NSDictionary *param = @{kCIInputBackgroundImageKey: image,
                                kCIInputImageKey: overlay
                                };
        CIFilter *filter = [CIFilter filterWithName:@"CISourceOverCompositing" withInputParameters:param];
        CGRect cropRect = image.extent;
        return [filter.outputImage imageByCroppingToRect:cropRect];
    };

}

//滤镜组合
Filter composeFilters(Filter filter1, Filter filter2){
    return ^(CIImage *image){
        return filter2(filter1(image));
    };
}

@implementation NSArray (Filter)


- (Filter)combine{
    
    if (self.count == 1) {
        return self.firstObject;
    }else if (self.count == 2){
        return composeFilters(self[0], self[1]);
    }else{
        Filter resutlFunc = composeFilters(self[0], self[1]);
        for (int i = 2; i< self.count; i++) {
            
            if (i == self.count - 1) {
               return  composeFilters(resutlFunc, self[i]);
            }else{
                resutlFunc = composeFilters(resutlFunc, self[i]);
            }
        }
        return resutlFunc;
    }
}

@end





